from flask import Flask, request, json
from sqlalchemy import create_engine, Table
from sqlalchemy.orm import sessionmaker, declarative_base, scoped_session

app = Flask(__name__)

# 创建引擎，链接数据库
engine = create_engine('mysql+pymysql://root:admin@127.0.0.1:3306/mumu', echo=True)
# 打开数据库的连接会话
session = sessionmaker(engine)
# 保证线程安全
db_session = scoped_session(session)
# 获取基类
Base = declarative_base()

# 创建表结构
# class User(Base):
#     __tablename__ = 'user'
#     id = Column(Integer, primary_key=True)
#     username = Column(String(50))

# 创建表
# User.metadata.create_all(engine)

class User(Base):
    # 表结构反射加载
    __table__ = Table("user", Base.metadata, autoload_with=engine)

@app.route('/', methods=['POST'])
def login():
    result = db_session.query(User).filter(User.user_name == 'fiona_liu').first()
    # result = db_session.query(User).all()
    print(result.user_name)

    request_data = request.data
    request_data = json.loads(request_data)
    username = request_data["username"]
    password = request_data["password"]

    print(username)
    print(password)

    return dict(username=username, password=password)

if __name__ == '__main__':
    app.run(debug=True)